/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.ui;

import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.business.Service;
import com.anhndt.audiobook.entity.ItemEntity;
import com.anhndt.audiobook.parser.WebServicesParser;
import com.anhndt.audiobook.utils.DBUtil;
import com.anhndt.audiobook.utils.DialogUtil;
import com.anhndt.audiobook.utils.StringUtil;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import org.ksoap2.serialization.SoapObject;

/**
 *
 * @author Loki
 */
public final class RegisterForm extends Form implements ActionListener {

    Button mButtonRegister = new Button(Resource.CMD_REGISTER);
    TextField mUserName = new TextField();
    TextField mPasswd = new TextField();
    TextField mEmail = new TextField();
    Command mCommandBack = new Command(Resource.CMD_BACK);
    Command mCommandRegister = new Command(Resource.CMD_REGISTER);
    
    Form mBackForm;
    public RegisterForm(Form backForm) {
        super(Resource.CMD_REGISTER);
        
        mBackForm = backForm;
        
        Display.getInstance().setThirdSoftButton(false);
        setSelectCommandText("");
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        mUserName.setConstraint(TextField.ANY);
        mUserName.setInputMode("abc");
        mUserName.setHint(Resource.TXT_USER_NAME);
        mUserName.setPaintInputType(false);
        
        mPasswd.setConstraint(TextField.PASSWORD);
        mPasswd.setInputMode("abc");
        mPasswd.setHint(Resource.TXT_PASSWD);
        mPasswd.setPaintInputType(false);
        
        mEmail.setConstraint(TextField.EMAILADDR);
//        mEmail.setInputMode("abc");
        mEmail.setHint(Resource.TXT_EMAIL);
        mEmail.setPaintInputType(false);
        //tét
//        mUserName.setText("anhndt");
//        mPasswd.setText("12345678");

        mButtonRegister.setAlignment(Button.CENTER);
        mButtonRegister.setPressedStyle(mButtonRegister.getSelectedStyle());
        mButtonRegister.addActionListener(this);

        addComponent();
    }

    void addComponent() {
        int paddingMarginLeft = mButtonRegister.getUnselectedStyle().getPadding(LEFT) + mButtonRegister.getUnselectedStyle().getMargin(RIGHT);
        //Panel Account
        Label lblAccountName = new Label(Resource.TXT_ACCOUNT);
        Label lblPasswd = new Label(Resource.TXT_PASSWD);
        Label lblEmail = new Label(Resource.TXT_EMAIL);
        lblPasswd.getUnselectedStyle().setMargin(TOP, 8);
        lblEmail.getUnselectedStyle().setMargin(TOP, 8);
        Container panelCaption = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        panelCaption.addComponent(lblAccountName);
        panelCaption.addComponent(lblPasswd);
        panelCaption.addComponent(lblEmail);
        //panelCaption.getUnselectedStyle().setMargin(RIGHT, Display.getInstance().getDisplayWidth() / 10);

        Container panelText = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        panelText.addComponent(mUserName);
        panelText.addComponent(mPasswd);
        panelText.addComponent(mEmail);

        if (Display.getInstance().getDisplayWidth() >= 320) {
            panelCaption.getUnselectedStyle().setMargin(LEFT, paddingMarginLeft);
            panelText.getUnselectedStyle().setMargin(RIGHT, paddingMarginLeft);
        }

        Container panelAcc = new Container(new BorderLayout());
        panelAcc.addComponent(BorderLayout.WEST, panelCaption);
        panelAcc.addComponent(BorderLayout.CENTER, panelText);

        addComponent(panelAcc);
        addComponent(mButtonRegister);
        addCommand(mCommandBack);
        addCommand(mCommandRegister);
        setBackCommand(mCommandBack);
        addCommandListener(this);
    }


    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == mButtonRegister || evt.getSource() == mCommandRegister) {
            doRegister();
        } else if (evt.getCommand() == mCommandBack) {
            mBackForm.show();
        }
    }

    public static boolean validate(String mobile, String passwd, String email) {
        //3 is min passwd lenght
        //24 is max passwd lenght
        return (!StringUtil.isNullOrEmpty(mobile) && !StringUtil.isNullOrEmpty(passwd) && !StringUtil.isNullOrEmpty(email));
    }

    void doRegister() {
        System.out.println("Login");
        if (!validate(mUserName.getText(), mPasswd.getText(), mEmail.getText())) {
            DialogUtil.showErrorDialog(Resource.TXT_WARRING_NO_FILL_FULL_DATA);
            return;
        }
        //Check TextUser  + TextPasswd
        Thread t = new Thread() {

            public void run() {

                try {
                    String lastUserID = Util.userID;
                    AccountService mAccountService = new AccountService();
                    String message = mAccountService.doRegister(mUserName.getText(), mPasswd.getText(), mEmail.getText());
                    System.out.println("UserID : " + Util.userID);
                    if (Util.userID != null && !Util.userID.equals(lastUserID)) {
                        mBackForm.removeAll();
                        mBackForm = null;
                        //Login Successful
                        //Save User + pass into RMS
                        Util.username = mUserName.getText();
                        Util.passwd = mPasswd.getText();
                        
                        DBUtil.changeValue(DBUtil.DB_RECORD_HAVE_ACCOUNT, Resource.TXT_YES);
                        DialogUtil.showInfoDialog(message);
                        Indicator.hide();
                        //Show MainForm
                        new MainForm().show();
                    } else {
                        //Login Failed
//                        Indicator.hide();
                        DialogUtil.showInfoDialog(message);
                        Indicator.hide();
                    }
                } catch (Exception ex) {
                    System.out.println("***************************Faild service Login");
                    ex.printStackTrace();
                    DialogUtil.showErrorConnectServer();
                    Indicator.hide();
//                    DialogUtil.showInfoDialog(Resource.LOGIN_FAILED);
                } finally {
                }
            }
        };
        t.setPriority(Thread.MAX_PRIORITY);
        Indicator.show(Resource.LOGING_MESSAGE, t);
    }

    class AccountService {
        final String USER_ID = "i";
        final String MESSAGE = "msg";
        
        private WebServicesParser parser;
        Service service;

        void LoginParser() {
        }

        public String doRegister(String username, String passwd, String email) throws Exception {
            service = new Service(Service.METHOD_LOGIN);
            service.addProperty("u", username);
            service.addProperty("p1", passwd);
            service.addProperty("e", email);
            service.addProperty("y", "" + ItemEntity.TYPE_USER_REGISTER);

            parser = new WebServicesParser(service);

            //call service
            SoapObject response = parser.getResponse();
            System.out.println("[LicenceParser] response = " + response);
            String message = "";
            if (response != null) {
                SoapObject soap = (SoapObject) response.getProperty(0);

                message = parser.getProperty(soap, MESSAGE);
                String userID = parser.getProperty(soap, USER_ID);
                if (!StringUtil.isNullOrEmpty(userID) && !userID.equals("0")) {
                    Util.userID = userID;
                }

                Util.DO_LOGIN = true;
            }
            return message;
        }
    }
}
